import { Component, OnInit, Input, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { _HttpClient } from '@delon/theme';
import { SFSchema, SFUISchema, SFButton, SFValueChange, SFComponent } from '@delon/form';
import { SysKeyValueService } from '@api/sys/service/sysKeyValue.service';
import { SysKeyValue } from '@api/sys/model/sysKeyValue.model';

@Component({
  selector: 'app-sys-keyValue-edit',
  templateUrl: './edit.component.html',
})
export class SysKeyValueEditComponent implements OnInit {
  _data: SysKeyValue = {};
  @Input() set data(data: SysKeyValue) {
    this._data = data;
    if (data.keyPath) {
      const index = data.keyPath.lastIndexOf('/');
      this.parentKeyPath = data.keyPath.substring(0, index);
    }
    if (data.id) {
      this.schema.properties!.key.readOnly = true;
    } else {
      this.schema.properties!.key.readOnly = false;
    }
  }
  get data(): SysKeyValue {
    return this._data;
  }

  parentKeyPath: string = '';

  @ViewChild('sf', { static: false }) sf!: SFComponent;
  schema: SFSchema = {
    properties: {
      key: { type: 'string', title: '键' },
      value: { type: 'string', title: '值' },
      keyPath: { type: 'string', title: '键路径', readOnly: true },
      sort: { type: 'number', title: '排序' },
      enabled: {
        type: 'string',
        title: '是否有效',
        enum: [
          { label: '是', value: 1 },
          { label: '否', value: 0 },
        ],
        default: 1,
      },
      description: { type: 'string', title: '描述', maxLength: 140 },
      attr1: { type: 'string', title: '属性1', maxLength: 140 },
      attr2: { type: 'string', title: '属性2', maxLength: 140 },
      attr3: { type: 'string', title: '属性3', maxLength: 140 },
      attr4: { type: 'string', title: '属性4', maxLength: 140 },
      attr5: { type: 'string', title: '属性5', maxLength: 140 },
    },
    required: ['type', 'typeName', 'key', 'value'],
  };
  ui: SFUISchema = {
    '*': {
      spanLabelFixed: 100,
      grid: { span: 12 },
    },
    $enabled: {
      widget: 'radio',
      styleType: 'button',
      buttonStyle: 'solid',
    },
    $description: {
      widget: 'textarea',
      grid: { span: 24 },
    },
  };

  button: SFButton = {
    submit: '保存',
  };

  constructor(private msgSrv: NzMessageService, public http: _HttpClient, private keyValueService: SysKeyValueService) {}

  ngOnInit(): void {}

  save(value: SysKeyValue) {
    this.keyValueService.save(value).subscribe((res) => {
      this.msgSrv.success('保存成功');
    });
  }

  formValueChange(valueChange: SFValueChange) {
    if (valueChange.path == '/key') {
      this.sf.setValue('/keyPath', `${this.parentKeyPath}/${valueChange.pathValue}`);
    }
  }
}
